package com.foreknow.elm.service.impl;

import com.foreknow.elm.dao.CartDao;
import com.foreknow.elm.dao.impl.CartDaoImpl;
import com.foreknow.elm.po.Cart;
import com.foreknow.elm.service.CartService;
import com.foreknow.elm.util.DBUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CartServiceImpl implements CartService {

    private int a = 0;

    @Override
    public List<Cart> listCart(String userId, Integer businessId) {
        List<Cart> list = new ArrayList<>();
        CartDao dao = new CartDaoImpl();
        try {
            // 获取连接
            DBUtil.getConnection();
            // 调用dao方法
            list = dao.listCart(userId,businessId);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return list;
    }

    @Override
    public int saveCart(Cart cart) {
        CartDao dao = new CartDaoImpl();
        try {
            // 开启事务
            DBUtil.beginTransaction();
            // 获取连接
            DBUtil.getConnection();
            // 调用dao方法
            a = dao.saveCart(cart);
            // 提交事务
            DBUtil.commitTransaction();
            } catch (Exception e) {
            try {
                // 有异常时回滚事务
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return a;
    }

    @Override
    public int updateCart(Cart cart) {
        CartDao dao = new CartDaoImpl();
        try {
            // 开启事务
            DBUtil.beginTransaction();
            // 获取连接
            DBUtil.getConnection();
            // 调用dao方法
            a = dao.updateCart(cart);
            // 提交事务
            DBUtil.commitTransaction();
        } catch (Exception e) {
            try {
                // 有异常时回滚事务
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return a;
    }

    @Override
    public int removeCart(String userId, Integer businessId, Integer foodId) {
        CartDao dao = new CartDaoImpl();
        try {
            // 开启事务
            DBUtil.beginTransaction();
            // 获取连接
            DBUtil.getConnection();
            // 调用dao方法
            a = dao.removeCart(userId, businessId, foodId);
            // 提交事务
            DBUtil.commitTransaction();
        } catch (Exception e) {
            try {
                // 有异常时回滚事务
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return a;
    }


}
